using System;
using DL.Animation;
using UnityEngine;

namespace DL.Tools
{
    public class HeadTrack : MonoBehaviour
    {
        private Transform m_LookTarget;
        private Animator m_Animator;
        private Transform m_Self;
        
        [Header("数据配置组")]
        [SerializeField]
        protected float maxSightAngle = 45f;
        [SerializeField]
        protected float followSpeed = 4;
        [SerializeField]
        protected float weight = 1;
        [SerializeField]
        protected float bodyWeight = .3f;
        [SerializeField]
        protected float headWeight = .5f;
        [SerializeField]
        protected float eyesWeight = .7f;

        protected float currentWeight;
        private Vector3 targetPos;
        private float angle;

        private void Start()
        {
            m_Animator = GetComponent<Animator>();
            m_Self = transform;
        }

        private void OnAnimatorIK(int layerIndex)
        {
            if (m_LookTarget == null && m_Animator.GetCurrentAnimatorStateInfo(0).IsTag(AnimatorTag.Motion))
            {
                m_LookTarget = Camera.main.transform;
            }
            
            else if (!m_Animator.GetCurrentAnimatorStateInfo(0).IsTag(AnimatorTag.Motion))
            {
                m_LookTarget = null;
            }

            if (m_LookTarget != null)
            {
                angle = Vector3.Angle(m_LookTarget.position - m_Self.position, m_Self.forward);
                if (angle > maxSightAngle)
                {
                    targetPos = m_LookTarget.position;
                }
            }

            if (m_LookTarget != null && angle <= maxSightAngle)
            {
                currentWeight = Mathf.Clamp01(currentWeight + followSpeed * Time.deltaTime) * weight;
                m_Animator.SetLookAtWeight(currentWeight, bodyWeight, headWeight, eyesWeight);
                m_Animator.SetLookAtPosition(m_LookTarget.position);
            }
            else
            {
                currentWeight = Mathf.Clamp01(currentWeight - followSpeed * Time.deltaTime) * weight;
                m_Animator.SetLookAtWeight(currentWeight, bodyWeight, headWeight, eyesWeight);
                m_Animator.SetLookAtPosition(targetPos);
            }
        }
    }
}
